import {baseUrl} from "./config";
let flag = false;
export const request = ({url, data = {}, method = 'POST',loading=false}) => {
    return new Promise((resolve, reject) => {
        let key = uni.getStorageSync('key');
        let pId = uni.getStorageSync('p_id');
        key && (data['key'] = key);
        // data['key'] = 'bbb89a4f225b60ea27aebb8bbe9e866d'
        pId && (data['p_id'] = pId);
        /*if (loading) uni.showLoading({
            title:'加载中...'
        })*/
        uni.request({
            url: `${baseUrl}/api/${url}`,
            header: {
                'Content-Type': 'application/json'
            },
            method,
            data,
            success: res => {
                let data = res.data;
                switch (data.code) {
                    case 200:
                        resolve(res.data.datas);
                        break;
                    case 999:
                        uni.clearStorageSync();
                        if (flag) return false;
                        uni.showModal({
                            title:'提示',
                            showCancel:false,
                            content:'登陆过期，请重新登录',
                            success:({confirm})=>{
                                if (confirm){
                                    flag = false;
                                    uni.reLaunch({
                                        url:'/pages/login/login'
                                    })
                                }
                            },
                        })
                        flag = true;

                        reject(res.data);
                        break;
                    case 998:
                        /*  uni.navigateTo({
                              url:'/pages/device-activation/device-activation'
                          })*/
                        resolve(res.data.datas);
                        break;
                    default:
                        setTimeout(()=>{
                            reject(res.data.datas.error)
                            uni.showModal({
                                title:'提示',
                                content:res.data.datas.error,
                                showCancel:false
                            })
                        },200)
                }

            },

            fail: err => {
                uni.showToast({
                    title:'服务器异常',
                    icon:'none'
                })
                reject(err.errMsg)
            },
            complete:()=>{
                uni.hideLoading();
            }
        })
    })
}
